package com.rockbb.common.utilities.internet;

import java.lang.reflect.Proxy;
import java.net.MalformedURLException;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;

import javax.xml.namespace.QName;

import org.apache.log4j.Logger;
import org.codehaus.xfire.XFireFactory;
import org.codehaus.xfire.XFireRuntimeException;
import org.codehaus.xfire.aegis.AegisBindingProvider;
import org.codehaus.xfire.annotations.AnnotationServiceFactory;
import org.codehaus.xfire.annotations.jsr181.Jsr181WebAnnotations;
import org.codehaus.xfire.client.XFireProxy;
import org.codehaus.xfire.client.XFireProxyFactory;
import org.codehaus.xfire.jaxb2.JaxbTypeRegistry;
import org.codehaus.xfire.service.Endpoint;
import org.codehaus.xfire.service.Service;
import org.codehaus.xfire.transport.TransportManager;

import com.hanqinet.edm.ws.prnasia.dto.upload.ArrayOfTaskGroup;
import com.hanqinet.edm.ws.prnasia.dto.upload.ArrayOfWillSendTaskInfo;
import com.hanqinet.edm.ws.prnasia.dto.upload.TaskGroup;
import com.hanqinet.edm.ws.prnasia.dto.upload.WillSendTaskInfo;
import com.hanqinet.edm.ws.prnasia.webservice.service.Auth;
import com.hanqinet.edm.ws.prnasia.webservice.service.EDMServicePortType;

public class WebServiceLoader {

	private static Logger logger = Logger.getLogger(WebServiceLoader.class);
	private static XFireProxyFactory proxyFactory = new XFireProxyFactory(XFireFactory.newInstance().getXFire());
	private HashMap<QName, Endpoint> endpoints;
	private Service service;
	private QName qname, qnamebinding;
	private String serviceUrl;
	private Class clazz;

	public WebServiceLoader() {
		endpoints = new HashMap<QName, Endpoint>();
	}

	public void init(){
		logger.debug("method init");
		TransportManager tm = (XFireFactory.newInstance().getXFire().getTransportManager());
        HashMap<String, Boolean> props = new HashMap<String, Boolean>();
        props.put("annotations.allow.interface", true);
        AnnotationServiceFactory asf = new AnnotationServiceFactory(new Jsr181WebAnnotations(), tm, new AegisBindingProvider(new JaxbTypeRegistry()) );
        asf.setBindingCreationEnabled(false);
		service = asf.create(clazz, props);

        asf.createSoap11Binding(service, qnamebinding, "http://schemas.xmlsoap.org/soap/http");
        Endpoint endpoint = service.addEndpoint(qname, qnamebinding, serviceUrl);
        endpoints.put(qname, endpoint);
        logger.debug("method init complete");
	}

	public Object getEndpoint(Endpoint endpoint) {
        try {
            return proxyFactory.create(endpoint.getBinding(), endpoint.getUrl());
        } catch (MalformedURLException e) {
            throw new XFireRuntimeException("Invalid URL", e);
        }
    }
	
	public Object getEndpoint(QName name) {
        Endpoint endpoint = (Endpoint) endpoints.get(name);
        if (endpoint == null) {
            throw new IllegalStateException("No such endpoint!");
        }
        return getEndpoint(endpoint);
    }

    public Collection<Endpoint> getEndpoints() {
        return endpoints.values();
    }

    public QName getQname() {return qname;}
	public void setQname(QName n) {this.qname = n;}

	public QName getQnamebinding() {return qnamebinding;}
	public void setQnamebinding(QName n) {this.qnamebinding = n;}

	public String getServiceUrl() {return serviceUrl;}
	public void setServiceUrl(String s) {this.serviceUrl = s;}

	public Class getClazz() {return clazz;	}
	public void setClazz(Class c) {this.clazz = c;}

	/**
	 * Test cases
	 * 
	 * @param args
	 */
	public static void main(String[] args) { 

		while (1==1)
		{
			WebServiceLoader loader = new WebServiceLoader();

			//Initialiser for EDMServicePortType
			QName name 	= new QName("http://service.webservice.prnasia.ws.edm.hanqinet.com", "EDMServiceHttpPort");
	        QName namebinding 	= new QName("http://service.webservice.prnasia.ws.edm.hanqinet.com", "EDMServiceHttpBinding");
	        String url = "http://119.254.9.65:8081/smartedm/services/EDMService";
			loader.setQname(name);
			loader.setQnamebinding(namebinding);
			loader.setServiceUrl(url);
			loader.setClazz(EDMServicePortType.class);
			loader.init();

			//Authentication
			EDMServicePortType servicePort = (EDMServicePortType)loader.getEndpoint(name);
			XFireProxy proxy = (XFireProxy) Proxy.getInvocationHandler(servicePort);
			//proxy.getClient().addOutHandler(new Auth("mailman","!SavannahCat"));
			proxy.getClient().addOutHandler(new Auth("story","story"));

			//Start invokes
			
			/*1.查询任务组信息*/
			ArrayOfTaskGroup arrGroup = servicePort.getTaskGroupInfo();
			List<TaskGroup> groups = arrGroup.getTaskGroup();
			for (int i=0; i<groups.size(); i++) {
				TaskGroup group = groups.get(i);
				System.out.println("Group "+(i+1)+": "+group.getTaskGroupId().getValue()+", "
						+group.getTaskGroupNo().getValue()+", "+group.getTaskGroupName().getValue()
						+", "+group.getCreateBy().getValue()+", "+group.getCreateDate().getValue()
				);
			}

			/*ArrayOfWillSendTaskInfo arrTask = servicePort.getWillSendTaskInfo();
			List<WillSendTaskInfo> tasks = arrTask.getWillSendTaskInfo();
			for (int i=0; i<tasks.size(); i++) {
				WillSendTaskInfo task = tasks.get(i);
				System.out.println("Task "+(i+1)+": "+task.getTaskId().getValue()+", "+task.getTaskGroupId().getValue()+", "
						+task.getTaskName().getValue()+", "+task.getMailCount().getValue()
						+", "+task.getTemplateContentSize().getValue()
				);
			}*/
		}
	}

}
